package com.qf.zuoye0612.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @Author UNIQ7xi
 * @Date 2023/6/13 9:01
 * @Version v1.8
 **/
@RestController
@RequestMapping("/pick")
@Slf4j
public class PicknameController {

    public static final String PICKED_FILE_NAME = "C:\\myprogram\\pick.txt";
    public static final String ALL_FILE_NAME = "C:\\myprogram\\2301stu.txt";

    @GetMapping("/reset")
    public String reset() throws Exception {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(PICKED_FILE_NAME));
        bufferedWriter.write("");
        bufferedWriter.flush();
        bufferedWriter.close();
        return "重置完毕";
    }

    @GetMapping("/name")
    public String pickname(boolean flag) throws Exception {
        log.info("入参为:flag={}",flag);
        //1.获取所有学生名单,存放到list中
        List<String> nameList = fileToList(ALL_FILE_NAME);
        //2.根据flag进行不同处理
        if (flag){
            int index = new Random().nextInt(nameList.size());
            String name = nameList.get(index);
            log.info("中奖同学为:{}",name);
        }else {
            List<String> pickednameList = fileToList(PICKED_FILE_NAME);
            nameList.removeAll(pickednameList);
            if (nameList!=null&&nameList.size()>0){
                int index = new Random().nextInt(nameList.size());
                String name = nameList.get(index);
                log.info("中奖同学为:{}",name);
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(PICKED_FILE_NAME));
                bufferedWriter.write(name);
                bufferedWriter.newLine();
                bufferedWriter.flush();
                bufferedWriter.close();
                return name;
            }
        }
        return "都点完啦";
    }

    private List<String> fileToList(String file) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        ArrayList<String> list = new ArrayList<>();
        String name = null;
        while ((name=bufferedReader.readLine())!=null){
            list.add(name);
        }
        return list;
    }

}
